package com.ruoyi;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.task.MyPlanSchedule;
import com.ruoyi.system.timing.ScheduleTimingPool;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.util.FileUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;

/**
 * 启动程序
 *
 * @author ruoyi
 */
@Slf4j
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class RuoYiApplication {

    public static void main(String[] args) throws Exception {
        /**加载项目启动配置*/
        ConfigurableApplicationContext applicationContext = SpringApplication.run(RuoYiApplication.class, RuoYiApplication.loadStartConfigFile(args));
        MyPlanSchedule bean = applicationContext.getBean("myPlanSchedule", MyPlanSchedule.class);
        /**开启定时任务*/
        bean.startMyPlan();
        /**启动计时器*/
        ScheduleTimingPool.startTimingPool() ;
    }

    /**
     * 加载项目启动配置
     * 根据配置文件cfg.ini
     * @param args
     * @return String[] 启动配置
     * @throws IOException
     */
    public static String[] loadStartConfigFile(String[] args) throws IOException {
        HashSet<String> paramSet = new HashSet<>(Arrays.asList(args));
        File file = new File(new File("").getCanonicalPath() + "/config/cfg.ini");
        if (!file.exists()) {
            log.info("启动配置不存在，采用默认配置");
            new File(file.getParent()).mkdirs();
            try{
                boolean newFile = file.createNewFile();
                if (!newFile) {
                    log.info("创建启动配置文件失败！");
                }
            }catch (IOException e){
                log.info("创建启动配置文件异常,异常信息为 -> {}" ,e.getMessage());
            }
        }else {
            String startConfigInfo = FileUtil.readAsString(file);
            if (StringUtils.isNotBlank(startConfigInfo)) {
                log.info("启动配置文件参数为 -> {}" ,startConfigInfo);
                String[] startParam = startConfigInfo.split(" ");
                paramSet.addAll(Arrays.asList(startParam));
            }else {
                log.info("启动配置文件为空，采用默认配置启动!");
            }
        }
        String[] typeOfStringArray = {} ;
        return new ArrayList<>(paramSet).toArray(typeOfStringArray) ;
    }

}

